package org.acghub.demo.mongodb.manager;

import org.acghub.demo.mongodb.entity.TestEntity;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class TestEntityManager {

    private final AtomicLong idGenerator = new AtomicLong();

    private final Map<Long, TestEntity> cache = new ConcurrentHashMap<>(64);

    public TestEntity query(Long id) {
        return cache.get(id);
    }

    public TestEntity random() {
        if (cache.isEmpty()) {
            return null;
        }
        long i = ThreadLocalRandom.current().nextLong(0, cache.size());
        Map.Entry<Long, TestEntity> entry = cache.entrySet().stream().skip(i).findFirst().orElse(null);
        if (entry == null) {
            return generate();
        }
        return entry.getValue();
    }

    public TestEntity generate() {
        TestEntity entity = createEntity();
        cache.put(entity.getId(), entity);
        return entity;
    }


    private TestEntity createEntity() {
        return TestEntity.builder()
                .id(idGenerator.incrementAndGet())
                .name(UUID.randomUUID().toString())
                .description(UUID.randomUUID().toString())
                .age(ThreadLocalRandom.current().nextInt(1, 100))
                .score(ThreadLocalRandom.current().nextDouble(0, 1000))
                .active(ThreadLocalRandom.current().nextBoolean())
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .tags(List.of(
                        UUID.randomUUID().toString(),
                        UUID.randomUUID().toString(),
                        UUID.randomUUID().toString()
                ))
                .properties(Map.of(
                        UUID.randomUUID().toString(), UUID.randomUUID().toString(),
                        UUID.randomUUID().toString(), UUID.randomUUID().toString(),
                        UUID.randomUUID().toString(), UUID.randomUUID().toString()
                ))
                .build();
    }


}
